<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\my\controller;

use api\index\controller\CommonController;
use app\admin\model\MemberModel;
use app\admin\model\PayGoodsModel;
use app\admin\model\PayOrderModel;
use cmf\controller\RestBaseController;
use think\Request;
use think\validate\ValidateRule;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;
use think\Db;

class PayController extends RestBaseController
{
    protected $noNeedLogin = ['notify'];

    public function index($type=0)
    {
        $this->success('成功', PayGoodsModel::where('type', $type)->all());
    }


    public function pay(Request $request)
    {
        if (!$request->isPost()) {
            $this->error('请求方式错误');
        }
        $this->checkValidate($request->param(), config('check.id'));
        if (!$payGoods = PayGoodsModel::get($request->id)) {
            $this->error('数据不存在');
        }
        $no = PayOrderModel::findAvailableNo();
        //创建订单
        $payOrder = PayOrderModel::create([
            'pay_id'       => $request->id,
            'member_id'    => $this->getUserId(),
            'type'         => $payGoods->type,
            'name'         => $payGoods->pay_name,
            'price'        => $payGoods->price,
            'pay_order_sn' => $no,
        ]);
        if (!$payOrder) {
            $this->error('创建订单失败');
        }

        $order = [
            'out_trade_no' => $no,
//            'total_fee'    => $payGoods->price * 100, // **单位：分**
            'total_fee'    => 1, // **单位：分**
            'body'         => '聊币充值',
            'openid'       => $this->user['openid'],
        ];
        $pay = Pay::wechat(config('wechat.config'))->mp($order);
        $this->success('成功', $pay);
    }

    public function notify()
    {
        $pay = Pay::wechat(config('wechat.config'));
        try {
            $data = $pay->verify(); // 验签
//            if ($data->return_code !== "SUCCESS"){
//                return $pay->success()->send();
//            }
            // 找到对应的订单
            $order = PayOrderModel::where('pay_order_sn', $data->out_trade_no)->find();
            if ($order->status == PayOrderModel::PAY_STATUS_SUCCESS) {
                return $pay->success()->send();
            }
            $this->orderPaid($order);
//            Log::debug('Wechat notify', $data->all());
        } catch (\Exception $e) {
            // $e->getMessage();
        }
        return $pay->success()->send();
    }

    public function orderPaid($order)
    {
        Db::startTrans();
        try {
            $member = MemberModel::get($order->member_id);
            $payGoods = PayGoodsModel::get($order->pay_id);
            if ($order->type == PayOrderModel::TYPE_VIP) { //充值vip
                if ($member->last_time && date("Y-m-d",$member->last_time) > date('Y-m-d',time())){
                       $time = $member->last_time;
                    }else{
                    $time = time();
                }
                //vip到期时间加上购买的vip天数
                $last_time = date('Y-m-d H:i:s',strtotime("+ " . $payGoods->pay_name . "day",$time));
                //修改成新的vip到期时间
                $member->last_time = strtotime($last_time);
                $member->is_vip = MemberModel::IS_VIP; //修改会员状态
                $member->save();
            }else{ //充值聊币
                //用户表增加聊币
                $member->setInc('talk_coin',$payGoods->pay_name);
                //修改聊币变动表
                CommonController::changeTalkCoin($order->member_id,$payGoods->pay_name,$member->talk_coin,$order->id);
            }
            //修改订单状态
            $order->status = PayOrderModel::PAY_STATUS_SUCCESS;
            $order->pay_time = time();
            $order->save();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
    }

    /**
     * 消费记录
     */
    public function expense_calendar()
    {
        if (! $this->request->isGet()){
            $this->error('请求方式错误');
        }
        $member = MemberModel::get($this->getUserId());
        $payOrder = $member->payOrder()->field('id,type,name,price,pay_time')->where('status',PayOrderModel::PAY_STATUS_SUCCESS)->order('pay_time desc')->paginate(config('verify.limit'));
        $this->success('成功',$payOrder);
    }


}
